package main

import (
	"fmt"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"gitverse.ru/z3nyk3y/investcalc/internal/config"
	"gitverse.ru/z3nyk3y/investcalc/internal/http-server/handlers/calc"
	"gitverse.ru/z3nyk3y/investcalc/internal/http-server/handlers/cors"
	mvLogger "gitverse.ru/z3nyk3y/investcalc/internal/http-server/middleware/logger"
)

const (
	envLocal = "local"
	envProd  = "prod"
)

func main() {
	cfg := config.MustCreateNewConfig()

	log := setupLogger(cfg.Env)

	log.Info("starting investcalc")
	log.Debug("Debug mode enabled")

	r := chi.NewRouter()

	calcRouter := chi.NewRouter()
	calcRouter.Use(middleware.RequestID)
	calcRouter.Use(mvLogger.New(log))
	calcRouter.Use(middleware.Recoverer)

	r.Mount("/api/v1", calcRouter)

	calc := calc.NewHandler(log).Calc().ServeHTTP
	cors := cors.NewHandler(log).Cors().ServeHTTP
	calcRouter.Post("/calc", calc)
	calcRouter.Options("/calc", cors)

	done := make(chan os.Signal, 1)
	signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
	srv := &http.Server{
		Addr:         cfg.HTTPServer.Addres,
		Handler:      r,
		ReadTimeout:  cfg.HTTPServer.Timeout,
		WriteTimeout: cfg.HTTPServer.Timeout,
		IdleTimeout:  cfg.HTTPServer.IdleTimeout,
	}

	go func() {
		if err := srv.ListenAndServe(); err != nil {
			log.Error("failed to start server")
		}
	}()

	log.Info(fmt.Sprintf("server started on %s", srv.Addr))

	<-done
	log.Info("stopping server")

}

func setupLogger(env string) *slog.Logger {
	var log *slog.Logger

	switch env {
	case envLocal:
		log = slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
	case envProd:
		log = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
	}

	return log

}
